package com.xb.system.constants;

import java.util.concurrent.*;

public class ThreadPoolManager {

    private static ThreadPoolExecutor executor;

    public static synchronized ExecutorService getExecutor(int threadPoolSize) {
        if (executor == null || executor.isShutdown()) {
            executor = new ThreadPoolExecutor(
                    threadPoolSize,
                    threadPoolSize,
                    60,
                    TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(1000),
                    new ThreadPoolExecutor.CallerRunsPolicy()
            );
        }
        return executor;
    }

    public static synchronized void shutdown() {
        //获取线程池中待执行任务的数量
        int taskSize = executor.getQueue().size();
        while (taskSize > 0) {
            try {
                Thread.sleep(1000);
                taskSize = executor.getQueue().size();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            executor.shutdownNow();
            throw new RuntimeException(e);
        }
    }

    public static void submitTask(Runnable task) {
        if (executor != null) {
            executor.submit(task);
        }
    }
}